#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <sys/epoll.h>
#include <netinet/tcp.h>
#include "InetAddress.h"
#include "Socket.h"
#include "Epoll.h"
#include "Channel.h"

void setnonblocking(int fd) {
    fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_NONBLOCK);
}

void str_toupper(char *buf, int len) {
    for (int i = 0; i < len; ++i)
        if (buf[i] >= 'a' && buf[i] <= 'z')
            buf[i] -= 32;
}

int main(int argc, char* argv[]) {
    // if (argc != 3) {
    //     printf("usage: ./tcpepoll ip port\n");
    //     return -1;
    // }

    Socket servsock(createnonblocking());
    servsock.setkeepalive(true);
    servsock.setreuseaddr(true);
    servsock.setreuseport(true);
    servsock.settcpnodelay(true);

    InetAddress servaddr("127.0.0.1",atoi("5085"));
    servsock.bind(servaddr);
    servsock.listen();

    
    Epoll epoll;
    Channel *servchannel = new Channel(&epoll,servsock.fd());
    servchannel->setreadcallback(std::bind(&Channel::newconnection,servchannel,&servsock));
    servchannel->enablereading();

    epoll.updatechannel(servchannel);
    

    std::vector<Channel*> events;

    while (1) {

        events = epoll.loop();

        for (auto ch : events) {
            ch->handleevent();
        }
    }

    //close(listenfd);
    return 0;
}
